package com.tycmc.signelectroniccontracts.logic.renzheng;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;

import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.IDCardParams;
import com.baidu.ocr.sdk.model.IDCardResult;
import com.baidu.ocr.sdk.model.Word;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.meiya.cunnar.opencloud.livingcertificationkit.LivingCertificationHelper;
import com.meiya.cunnar.opencloud.livingcertificationkit.VerifyCallback;
import com.tycmc.signelectroniccontracts.act.htong.ActHtList;
import com.tycmc.signelectroniccontracts.act.renzheng.ActPeopleRenzhen;
import com.tycmc.signelectroniccontracts.act.renzheng.ActQiyeRenZheng;
import com.tycmc.signelectroniccontracts.tools.AppData;
import com.tycmc.signelectroniccontracts.tools.base.LogicParent;
import com.tycmc.signelectroniccontracts.tools.htmlcommit.HtCommitEntity;
import com.tycmc.signelectroniccontracts.tools.htmlcommit.HtmlType;
import com.tycmc.signelectroniccontracts.tools.images.UrlPath;
import com.tycmc.signelectroniccontracts.tools.manager.AppManager;
import com.tycmc.signelectroniccontracts.tools.net.NetUrl;
import com.tycmc.signelectroniccontracts.tools.net.NetWorkUtils;
import com.tycmc.signelectroniccontracts.tools.net.RequestAction;
import com.tycmc.signelectroniccontracts.tools.net.result.NetworkResult;
import com.tycmc.signelectroniccontracts.tools.net.result.ProGressUpDataListen;
import com.tycmc.signelectroniccontracts.tools.net.tools.Json;
import com.tycmc.signelectroniccontracts.tools.other.TextShow;
import com.tycmc.signelectroniccontracts.tools.other.TyTypenum;
import com.tycmc.signelectroniccontracts.tools.show.AlertDialog;
import com.tycmc.signelectroniccontracts.tools.show.LogShow;
import com.tycmc.signelectroniccontracts.tools.show.ProDialog;
import com.tycmc.signelectroniccontracts.tools.show.ToastShow;
import com.tycmc.signelectroniccontracts.tools.store.FileStore;
import com.tycmc.signelectroniccontracts.tools.store.SharePre;
import com.tycmc.signelectroniccontracts.tools.store.SharePreName;
import com.tycmc.signelectroniccontracts.tools.times.DataTimer;

import org.json.JSONException;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PrePeopleRenzhen extends LogicParent {

    private final String filePath;
    private ActPeopleRenzhen context;
    private PeopleRenZhenInterface pre;
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message message) {
            handler.sendEmptyMessageDelayed(message.what - 1, 1000);//设置1s延迟
            pre.edCode(message.what);

            return true;
        }
    });

    public PrePeopleRenzhen(PeopleRenZhenInterface pre, Intent intent, String filePath) {
        this.pre = pre;
        context = ((ActPeopleRenzhen) pre);
        pre.shoujihao(SharePre.getString(SharePreName.modile, ""));
        this.filePath = filePath;
    }

    //获取验证码
    public void getcode() {
        RequestAction action = new RequestAction(NetUrl.getVerificationCode);
        action.putBody("clientArchiveNo", SharePre.getString(SharePreName.clientArchiveNo, ""));
        action.putBody("verificationCodeType", "1");
        final ProDialog dialog = new ProDialog(context, "");
        dialog.show();
        new NetWorkUtils(context).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                handler.sendEmptyMessage(60);
            }

            @Override
            public void failed(Object data) {
                dialog.dismiss();
                handler.sendEmptyMessage(60);
            }
        });


    }

    public void destory() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);//移除handler倒计时
        }
    }



    public void onResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == TyTypenum.renlianTouxiang && resultCode == Activity.RESULT_OK) {
            Serializable extra = data.getSerializableExtra(CameraActivity.KEY_CONTENT_TYPE);
            if (CameraActivity.CONTENT_TYPE_ID_CARD_FRONT.equals(extra)) {
                if (new File(UrlPath.imagePath + IDCardParams.ID_CARD_SIDE_FRONT + filePath + ".png").exists()) {
                    pre.sendPicterBefore(UrlPath.imagePath + IDCardParams.ID_CARD_SIDE_FRONT + filePath + ".png");
                    recode(IDCardParams.ID_CARD_SIDE_FRONT, UrlPath.imagePath + IDCardParams.ID_CARD_SIDE_FRONT + filePath + ".png");
                }
            }
        }
        if (requestCode == TyTypenum.renlianBack && resultCode == Activity.RESULT_OK) {
            Serializable extra = data.getSerializableExtra(CameraActivity.KEY_CONTENT_TYPE);
            if (CameraActivity.CONTENT_TYPE_ID_CARD_BACK.equals(extra)) {
                pre.sendPicterEnd(UrlPath.imagePath + IDCardParams.ID_CARD_SIDE_BACK + filePath + ".png");

            }
        }
    }

    private void recode(final String positon, final String url) {
// 行驶证识别参数设置
        IDCardParams param = new IDCardParams();

// 设置image参数
        param.setImageFile(new File(url));
// 设置其他参数
        param.setIdCardSide(positon);
        // 设置方向检测
        param.setDetectDirection(true);
        // 设置图像参数压缩质量0-100, 越大图像质量越好但是请求时间越长。 不设置则默认值为20
        param.setImageQuality(20);
        param.setDetectRisk(true);
        final ProDialog dialog = new ProDialog(context, "正在识别");
        dialog.show();
        OCR.getInstance(context).recognizeIDCard(param, new OnResultListener<IDCardResult>() {
            @Override
            public void onResult(IDCardResult result) {
                // 调用成功，返回OcrResponseResult对象.
                LogShow.i("成功", result.getLogId() + "\n" + result.getJsonRes());
                dialog.dismiss();
                Map map = new HashMap();

                pre.initData(getWords(result.getName(), ""),getWords(result.getGender(), ""), getWords(result.getEthnic(), ""), DataTimer.getStringData("yyyy-MM-dd", DataTimer.getLongTime(getWords(result.getBirthday(), ""), "yyyyMMdd")), getWords(result.getIdNumber(), ""), getWords(result.getAddress(), ""));
            }

            @Override
            public void onError(OCRError error) {
                dialog.dismiss();
                if (new File(url).exists()) {
                    new File(url).delete();
                }
//                ToaShow.popupToast(context,error.getMessage() + "(" + error.getErrorCode() + ")");
                LogShow.i("失败", error.getLogId() + "\n" + error.getErrorCode() + "\n" + error.getMessage());
                // 调用失败，返回OCRError对象
            }
        });
    }

    private String getWords(Word word, String str) {
        if (word != null) {
            return word.getWords();
        }
        return str;
    }

    public void huotijiance(final String name, final String idcard) {
        RequestAction action = new RequestAction(NetUrl.getCunnarToken);
        final ProDialog dialog = new ProDialog(context, "");
        dialog.show();
        new NetWorkUtils(context).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                huoti(name, idcard,  TextShow.valueOf(data.get("token")));
            }

            @Override
            public void failed(Object data) {
                ToastShow.popupToast(data+"");
                new AlertDialog(context).builder().setTitle("温馨提示").setMsg("认证失败需要重新进行认证").setPositiveButton("认证", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pre.sendRenlianshibie(name,idcard);
                    }
                }).setNegativeButton("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        context.exit();
                    }
                }).show();
                dialog.dismiss();
            }
        });

    }

    public void huoti(final String name, final String idcard, String accessToken) {
        LivingCertificationHelper
                .verify(context, /*此处接收姓名*/name, /*此处接收身份证号*/idcard, /*此处接收AccessToken*/accessToken, /*此处接收AppKey*/AppData.appkey,
                        new VerifyCallback() {
                            @Override
                            public void onVerifyCompleted(boolean verify, String msg, byte[] picResult) {
                                LogShow.i("msg",msg+"");
                                if (verify) {
                                    RequestAction action = new RequestAction(NetUrl.savePersonaalFace);
                                    action.putBody("clientArchiveNo", SharePre.getString(SharePreName.clientArchiveNo, ""));
                                    action.putBody("clientTypeID", SharePre.getString(SharePreName.clientTypeID, ""));
                                    if (null != picResult) {
                                        String save = FileStore.save(System.currentTimeMillis() + ".png", picResult);
                                        File[] files = new File[1];
                                        files[0] = new File(save);
                                        action.putBody("multipartFiles", files);
                                    }
                                    final ProDialog dialog = new ProDialog(context, "");
                                    dialog.show();
                                    new NetWorkUtils(context).upLoadProgress(action, new ProGressUpDataListen() {
                                        @Override
                                        public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {

                                        }

                                        @Override
                                        public void sucess(Map<String, Object> data, String str) {
                                            dialog.dismiss();

                                            context.start(new Intent(context, ActHtList.class));
                                            AppManager.getAppManager().finishAllActivity();
                                        }

                                        @Override
                                        public void failed(Object data) {
                                            ToastShow.popupToast(data + "");

                                            dialog.dismiss();
                                            new AlertDialog(context).builder().setTitle("温馨提示").setMsg("认证失败需要重新进行认证").setPositiveButton("认证", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    pre.sendRenlianshibie(name,idcard);
                                                }
                                            }).setNegativeButton("取消", new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {
                                                    context.exit();
                                                }
                                            }).show();
                                        }
                                    });

                                } else {
                                    ToastShow.popupToast(msg);
                                    new AlertDialog(context).builder().setTitle("温馨提示").setMsg("认证失败需要重新进行认证").setPositiveButton("认证", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            pre.sendRenlianshibie(name,idcard);
                                        }
                                    }).setNegativeButton("取消", new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            context.exit();
                                        }
                                    }).show();
                                }

                            }
                        });
    }

    public void upData(final Map map) {
        RequestAction action = new RequestAction(NetUrl.savePersonalInfo);
        action.putBodyAll(map);
        action.putBody("clientArchiveNo", SharePre.getString(SharePreName.clientArchiveNo, ""));
            File[] files = new File[2];
            files[0] = (File) map.get("fileBefore");
            files[1] = (File) map.get("backFile");
            action.putBody("multipartFiles", files);
        final ProDialog dialog = new ProDialog(context, "");
        dialog.show();
        new NetWorkUtils(context).upLoadProgress(action, new ProGressUpDataListen() {
            @Override
            public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
                LogShow.i("正在上传",bytesWritten+"bytesWritten  "+contentLength+"  contentLength");
            }

            @Override
            public void sucess(Map<String, Object> data, String str) {
                dialog.dismiss();
                pre.sendRenlianshibie(TextShow.valueOf(map.get("clientName")),TextShow.valueOf(map.get("idcNo")));

            }

            @Override
            public void failed(Object data) {
                ToastShow.popupToast(data+"");
                dialog.dismiss();
            }
        });

    }

    public void getInfo() {
        RequestAction action = new RequestAction(NetUrl.getCompanyInfo);
        action.putBody("clientArchiveNo", SharePre.getString(SharePreName.clientArchiveNo, ""));
        action.putBody("clientTypeID", SharePre.getString(SharePreName.clientTypeID, ""));
        final ProDialog dialog = new ProDialog(context, "");
        dialog.show();
        new NetWorkUtils(context).postJson(action, new NetworkResult() {
            @Override
            public void sucess(Map<String, Object> data, String str) {

                pre.sendRenlianshibie(TextShow.valueOf(data.get("clientName")),TextShow.valueOf(data.get("idcNo")));
                dialog.dismiss();
            }

            @Override
            public void failed(Object data) {
                dialog.dismiss();
            }
        });
    }

    public interface PeopleRenZhenInterface {

        void sendPicterBefore(String before);

        void sendPicterEnd(String end);

        void edCode(int number);//倒计时

        void shoujihao(String modile);
        void initData(String clientName,String sex,String nation,String dateOfBirth,String idcNo,String address);

        void sendRenlianshibie(String clientName,String idcNo);
    }
}
